/**
 * Created by John on 2016/7/13.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();

mongo.connect('mongodb://localhost/', function (err, db) {
   var myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        sortWordsAscending(collection);
        sortWordsDescending(collection);
        sortWordsAscAndSize(collection);
        close(myDB);
    });
});

function sortWordsAscending(collection) {
    var query = {first: 'w'};
    var sorter = {word: 1};
    var cursor = collection.find(query);
    cursor.sort(sorter);
    displayCurosr(cursor, 'W words ordered ascedning:');
}

function sortWordsDescending(collection) {
    var query = {first: 'w'};
    var sorter = {word: -1};
    var cursor = collection.find(query);
    cursor.sort(sorter);
    displayCurosr(cursor, 'W words ordered descending:');
}

function sortWordsAscAndSize(collection) {
    var query = {first: 'w'};
    var sorter = {word: 1, size: -1};
    var cursor = collection.find(query);
    cursor.sort(sorter);
    displayCurosr(cursor, 'W words ordered first by last letter and than by size:');
}

function close(myDB) {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}

function displayCurosr(cursor, msg) {
    cursor.toArray(function (err, items) {
        var wordStr = '';
        for (var i in items) {
            wordStr += items[i].word + ',';
        }
        if (wordStr.length > 33) {
            wordStr = wordStr.slice(0, 33) + '...';
        }
        console.log(msg);
        console.log(wordStr);
        console.log();
    });
}